const api = require('../../utils/api')
const util = require('../../utils/util')

Page({
  data: {
    recordDays: 0,
    totalRecords: {
      glucose: 0,
      bloodPressure: 0,
      weight: 0
    },
    weekdayRecords: [],
    currentMonth: '',
    displayMonth: '',
    currentType: 'all',
    records: [],
    recordGroups: []
  },

  onLoad() {
    // 初始化当前月份
    const now = new Date()
    const currentMonth = util.formatYearMonth(now)
    const displayMonth = util.formatMonthCN(now)
    
    this.setData({
      currentMonth,
      displayMonth
    })
    
    this.fetchOverviewData()
    this.fetchRecords(currentMonth, 'all')
  },

  onShow() {
    // 每次显示页面时刷新数据
    this.fetchOverviewData()
    this.fetchRecords(this.data.currentMonth, this.data.currentType)
  },

  // 获取概览数据
  async fetchOverviewData() {
    try {
      // 获取记录天数和总记录数
      const overviewResult = await api.health.getRecordOverview()
      
      if (overviewResult) {
        this.setData({
          recordDays: overviewResult.recordDays || 0,
          'totalRecords.glucose': overviewResult.glucoseCount || 0,
          'totalRecords.bloodPressure': overviewResult.bloodPressureCount || 0,
          'totalRecords.weight': overviewResult.weightCount || 0
        })
      }
      
      // 获取近7天的记录趋势
      const weekTrendResult = await api.health.getWeekTrend()
      
      if (weekTrendResult && weekTrendResult.days) {
        // 计算最大记录数，用于计算柱状图高度
        const maxCount = Math.max(...weekTrendResult.days.map(day => day.count))
        const baseHeight = 150 // 最大高度
        
        const weekdayRecords = weekTrendResult.days.map(day => ({
          ...day,
          label: day.weekday,
          height: day.count > 0 ? (day.count / maxCount) * baseHeight : 20 // 至少20rpx高
        }))
        
        this.setData({ weekdayRecords })
      }
    } catch (err) {
      console.error('获取概览数据失败:', err)
    }
  },

  // 获取记录数据
  async fetchRecords(month, type) {
    try {
      wx.showLoading({ title: '加载中...' })
      
      const params = { month }
      
      if (type !== 'all') {
        params.type = type
      }
      
      const result = await api.health.getRecords(params)
      
      if (result && result.list) {
        // 处理记录数据
        const records = result.list.map(record => {
          // 根据类型设置短名称
          const typeShortMap = {
            'glucose': '糖',
            'bloodPressure': '压',
            'weight': '重'
          }
          
          // 根据类型设置单位
          const unitMap = {
            'glucose': 'mmol/L',
            'bloodPressure': 'mmHg',
            'weight': 'kg'
          }
          
          // 根据类型设置标题
          const titleMap = {
            'glucose': '血糖',
            'bloodPressure': '血压',
            'weight': '体重'
          }
          
          // 根据类型格式化值
          let valueText = ''
          if (record.type === 'bloodPressure' && record.systolic && record.diastolic) {
            valueText = `${record.systolic}/${record.diastolic}`
          } else {
            valueText = record.value || '--'
          }
          
          // 格式化时间显示
          const timeDisplay = util.formatTime(record.hour, record.minute)
          
          return {
            ...record,
            typeShort: typeShortMap[record.type] || '?',
            title: titleMap[record.type] || '未知记录',
            value: valueText,
            unit: unitMap[record.type] || '',
            timeDisplay
          }
        })
        
        this.setData({ records })
        
        // 按日期分组
        this.groupRecordsByDate(records)
      } else {
        this.setData({ 
          records: [],
          recordGroups: [] 
        })
      }
      
      wx.hideLoading()
    } catch (err) {
      console.error('获取记录数据失败:', err)
      wx.hideLoading()
      wx.showToast({
        title: '获取数据失败',
        icon: 'none'
      })
    }
  },

  // 按照日期分组记录
  groupRecordsByDate(records) {
    // 创建日期分组对象
    const dateGroups = {}
    
    // 将记录按照日期分组
    records.forEach(record => {
      if (!dateGroups[record.date]) {
        dateGroups[record.date] = {
          date: record.date,
          dateDisplay: util.formatDateCN(new Date(record.date)),
          records: []
        }
      }
      
      dateGroups[record.date].records.push(record)
    })
    
    // 将分组对象转换为数组，并按日期排序
    const recordGroups = Object.values(dateGroups).sort((a, b) => {
      return new Date(b.date) - new Date(a.date)
    })
    
    this.setData({ recordGroups })
  },

  // 月份选择变化
  onMonthChange(e) {
    const month = e.detail.value
    const displayMonth = util.formatMonthCN(new Date(month + '-01'))
    
    this.setData({
      currentMonth: month,
      displayMonth
    })
    
    this.fetchRecords(month, this.data.currentType)
  },

  // 筛选类型变化
  filterByType(e) {
    const type = e.currentTarget.dataset.type
    
    this.setData({ currentType: type })
    
    this.fetchRecords(this.data.currentMonth, type)
  },

  // 查看记录详情
  viewRecordDetail(e) {
    const { id, type } = e.currentTarget.dataset
    
    wx.navigateTo({
      url: `/pages/recordDetail/recordDetail?id=${id}&type=${type}`
    })
  },

  // 前往记录页面
  goToRecord() {
    wx.showActionSheet({
      itemList: ['记录血糖', '记录血压', '记录体重'],
      success: (res) => {
        const types = ['glucose', 'bloodPressure', 'weight']
        const selectedType = types[res.tapIndex]
        
        wx.navigateTo({
          url: `/pages/record/record?type=${selectedType}`
        })
      }
    })
  },

  // 导出健康数据
  exportHealthData() {
    wx.showActionSheet({
      itemList: ['导出Excel', '导出PDF'],
      success: (res) => {
        // 实际会调用导出API
        wx.showLoading({ title: '准备导出...' })
        
        setTimeout(() => {
          wx.hideLoading()
          wx.showToast({
            title: '导出成功',
            icon: 'success'
          })
        }, 1500)
      }
    })
  }
}) 